import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";
import requireTransform from "vite-plugin-require-transform";
import Components from "unplugin-vue-components/vite";
//查看打包文件体积
import { visualizer } from "rollup-plugin-visualizer"; //查看打包后文件分析
//按需引入
import AutoImport from "unplugin-auto-import/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { VantResolver } from "@vant/auto-import-resolver";
//预打包
// import OptimizationPersist from 'vite-plugin-optimize-persist'
// import PkgConfig from 'vite-plugin-package-config'
// 图片压缩
// import { ViteImageOptimizer } from "vite-plugin-image-optimizer";//vite-plugin-image-optimizer
// import minipic from "vite-plugin-minipic";//vite-plugin-minipic
import viteImagemin from "vite-plugin-imagemin";
//gzip压缩
import compression from "vite-plugin-compression";
//网络优化
import mkcert from "vite-plugin-mkcert";
//setup配置name
import VueSetupExtend from "vite-plugin-vue-setup-extend";

// import vitePrerender from "vite-plugin-prerender";
import { autoComplete, Plugin as importToCDN } from "vite-plugin-cdn-import";
// const dependencies = require("./package.json").dependencies;
export default defineConfig({
  base: "./",
  build: {
    outDir: "tigerSlot",
    cssCodeSplit: true, //css代码分割
    emptyOutDir: true, // 打包时先清空上一次构建生成的目录
    assetsDir: "tigerSlot/assets",

    // modulePreload: {
    //   polyfill: true,
    // },
    assetsInlineLimit: 1024 * 10, //图片小于10kb base64转码
    // 在这里关闭严格模式
    minify: "terser", // 可以是 'terser' 或 'esbuild'
    sourcemap: false, //关闭sourcemap
    terserOptions: {
      compress: {
        // 关闭严格模式
        drop_debugger: true,
        drop_console: true,
        pure_funcs: ["console.log"], // 移除console.log
      },
    },

    rollupOptions: {
      cache: true,
      treeshake: true, // 开启 Tree Shaking，消除未使用的代码，减小最终的包大小
      // external: ['Vant'],  // 将vue排除在bundle外部
      // external: [
      //   "vue",
      //   "element-plus",
      //   "@element-plus/icons-vue",
      //   "vuex",
      //   "axios",
      //   "vue-router",
      //   "vant",
      //   "vue3-seamless-scroll",
      //   "vue-i18n",
      //   "qrcode",
      //   "vue-clipboard2"
      // ],
      output: {
        // 根据不同的js库 拆分包，减少index.js包体积
        entryFileNames: `assets/js/[name].[hash].js`,
        chunkFileNames: `assets/js/[name].[hash].js`,
        assetFileNames: `assets/[ext]/[name].[hash].[ext]`,
        compact: true,
        manualChunks(id) {
          if (id.includes("node_modules")) {
            console.log(id.toString().split("node_modules/")[1], "ooo");
            debugger;
            return id
              .toString()
              .split("node_modules/")[1]
              .split("/")[0]
              .toString();
          }
        },
      },
    },
    cssMinify: true,
  },

  plugins: [
    // ,ElementPlusResolver()
    cssInjectedByJsPlugin(), //js css合并
    // PkgConfig(),
    // OptimizationPersist(),//预打包
    AutoImport({
      resolvers: [VantResolver(), ElementPlusResolver()],
    }),
    // vitePrerender({
    //   routes: ['/','/home','/Star'],
    //   // 静态文件目录
    //   staticDir: path.join(__dirname, 'tigerSlot'),
    //   // 可选 - 使用 html-minifier (https://github.com/kangax/html-minifier)
    //   // 缩小生成的 HTML。
    //   // 选项参考：https://github.com/kangax/html-minifier#options-quick-reference
    //   minify : {
    //     collapseBooleanAttributes : true ,
    //     collapseWhitespace : true ,
    //     decodeEntities : true ,
    //     keepClosingSlash : true ,
    //     sortAttributes : true ,
    //   } ,

    // }),
    Components({
      //
      resolvers: [VantResolver(), ElementPlusResolver()],
    }),
    compression({
      verbose: true, // 是否在控制台输出压缩结果
      disable: false, // 是否禁用 gzip 压缩
      threshold: 10240, // 压缩文件的大小阈值（以字节为单位）
      algorithm: "gzip", // 压缩算法
      ext: ".gz", // 压缩文件的后缀名
      deleteOriginFile: false, // 是否删除原文件
      // 需要压缩的文件类型
      filter: (filename) => {
        return /(\.js$|\.css$|\.html$|\.json$)/.test(filename);
      },
    }),
    vue(),
    mkcert(),
    VueSetupExtend(),
    viteImagemin({
      gifsicle: { optimizationLevel: 3, interlaced: true },
      mozjpeg: { quality: 70, progressive: true },
      optipng: {
        optimizationLevel: 5.5,
      },
      pngquant: {
        quality: [0.65, 0.9],
        speed: 4,
      },
      webp: { quality: 70 },
      svgo: {
        plugins: [
          {
            name: "removeViewBox",
          },
          {
            name: "removeEmptyAttrs",
            active: false,
          },
        ],
      },
    }),
    // minipic({
    //   sharpOptions: {
    //     png: {
    //       quality: 65,
    //     },
    //     jpeg: {
    //       quality: 65,
    //     },
    //     jpg: {
    //       quality: 65,
    //     },
    //     avif: {
    //       quality: 75,
    //     },
    //     webp: {
    //       quality: 65,
    //     },
    //     gif: {
    //       // quality: 65
    //       interFrameMaxError: 28,
    //     },
    //   },
    //   convert: [
    //     { from: "png", to: "webp" },
    //     { from: "jpg", to: "webp" },
    //     { from: "jpeg", to: "jpg" },
    //   ],
    //   cache: true,
    // }),
    // ViteImageOptimizer({
    //   png: { quality: 65 },
    //   jpeg: { quality: 65 },
    //   jpg: { quality: 65 },
    //   webp: { quality: 65 },

    // }), //图片压缩

    requireTransform({
      fileRegex: /.ts$|.vue$/,
    }),
    visualizer({
      open: true, //注意这里要设置为true，否则无效
    }),
    importToCDN({
      // prodUrl: 'https://cdn.jsdelivr.net/npm/{name}@{version}/{path}',
      modules: [
        // autoComplete('vue'),
        // autoComplete('axios'),
        // {
        //   name: 'vue',
        //   var: 'Vue',
        //   path: `https://unpkg.com/vue@3.3.4/dist/vue.global.js`,
        // },
        // {
        //   name: 'vue-router',
        //   var: 'VueRouter',
        //   path: `https://unpkg.com/vue-router@4.2.5/dist/vue-router.global.js`,
        // },
        // {
        //   name: 'vue-demi',
        //   var: 'VueDemi',
        //   path: `https://unpkg.com/vue-demi@0.14.6`,
        // },
        // {
        //   name: 'vue-i18n',
        //   var: 'VueI18n',
        //   path: 'https://unpkg.com/vue-i18n@9.10.1/dist/vue-i18n.global.js',
        // },
        // {
        //   name: 'element-plus',
        //   var: 'ElementPlus',
        //   path: 'https://unpkg.com/element-plus@2.6.1/dist/index.full.js',
        //   css: 'https://unpkg.com/element-plus@2.6.1/dist/index.css'
        // },
        // {
        //   name: 'vant',
        //   var: 'Vant',
        //   path: 'https://fastly.jsdelivr.net/npm/vant@4.8.7',
        //   css: 'https://fastly.jsdelivr.net/npm/vant@4.8.7/lib/index.css'
        // },
      ],
    }),
  ],

  server: {
    host: "192.168.12.111",
    https: false,
    // 跨域设置允许
    port: 8088,
    cors: true,
    proxy: {
      "/api": {
        target: "https://jsgame.live",
        changeOrigin: true,
        rewrite: (path) => {
          console.log(path, path.replace(/^\/api/, ""), "uuu");

          return path.replace(/^\/api/, "");
        },
      },
      "/API": {
        target: "https://c.u7games.com/",
        changeOrigin: true,
        rewrite: (path) => {
          console.log(path, path.replace(/^\/API/, ""), "uuu");

          return path.replace(/^\/API/, "");
        },
      },
    },
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
  optimizeDeps: {
    // 预加载的依赖列表
    exclude: [],
    include: [
      "element-plus/es",
      "element-plus/es/components/dialog/style/index",
      "element-plus/es/components/button/style/index",
      "element-plus/es/components/dropdown-item/style/index",
      "element-plus/es/components/dropdown-menu/style/index",
      "element-plus/theme-chalk/el-dropdown-menu.css",
      "element-plus/theme-chalk/el-dropdown-item.css",
      "element-plus/theme-chalk/el-message.css",
      "element-plus/theme-chalk/el-input.css",
      "element-plus/theme-chalk/el-pagination.css",
      "element-plus/theme-chalk/el-select.css",
      "element-plus/theme-chalk/el-scrollbar.css",
      "element-plus/theme-chalk/el-button.css",
      "element-plus/theme-chalk/el-button-group.css",
      "element-plus/theme-chalk/el-dropdown.css",
      "element-plus/theme-chalk/el-badge.css",
      "element-plus/theme-chalk/el-popper.css",
      "element-plus/theme-chalk/el-tag.css",
      "element-plus/theme-chalk/el-option-group.css",
      "element-plus/theme-chalk/el-option.css",
      "axios",
      "vant",
      "lodash-es",
      "element-plus",
      "vuex",
      "vue",
      "vue-router",
      "vue3-seamless-scroll",
      "vue-i18n",
      "qrcode",
      "vue-clipboard2",
    ],
    // 预加载的依赖是否在生产环境中也可用
  },

  css: {
    // css预处理器
    preprocessorOptions: {
      scss: {
        // 引入 mixin.scss 这样就可以在全局中使用 mixin.scss中预定义的变量了
        // 给导入的路径最后加上 ;
        additionalData: '@import "@/assets/style/common.scss";',
      },
    },
    postcss: {
      plugins: [
        // postCssPxToRem({
        //   rootValue: 75, // 1rem，根据 设计稿宽度/10 进行设置
        //   propList: ["*"], // 需要转换的属性，这里选择全部都进行转换
        // }),
      ],
    },
  },
});
